package com.ctshk.rpc.order.season.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.ProductType;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.booking.enums.SupplierReserveTypeEnum;
import com.ctshk.rpc.booking.req.system.hotel.add.SupplierOrderSystemHotelAddReq;
import com.ctshk.rpc.booking.req.system.hotel.add.SupplierSystemOrderHotelCheckInAddReq;
import com.ctshk.rpc.booking.req.system.hotel.add.SupplierSystemOrderHotelTouristAddReq;
import com.ctshk.rpc.booking.service.ISupplierOrderService;
import com.ctshk.rpc.order.season.dto.SeasonOrderPayDTO;
import com.ctshk.rpc.order.season.dto.SeasonOrderTouristDataDTO;
import com.ctshk.rpc.order.season.dto.SeasonProductOrderHotelDTO;
import com.ctshk.rpc.order.season.entity.SeasonOrder;
import com.ctshk.rpc.order.season.entity.SeasonProductOrderHotel;
import com.ctshk.rpc.order.season.mapper.SeasonOrderMapper;
import com.ctshk.rpc.order.season.mapper.SeasonProductOrderHotelMapper;
import com.ctshk.rpc.order.season.service.ISeasonOrderTouristService;
import com.ctshk.rpc.order.season.service.ISeasonProductOrderHotelService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 套票-订单-酒店订单 服务实现类
 * </p>
 *
 * @author 杨林
 * @since 2021-03-24
 */
@DubboService
public class SeasonProductOrderHotelServiceImpl extends ServiceImpl<SeasonProductOrderHotelMapper, SeasonProductOrderHotel> implements ISeasonProductOrderHotelService {

    @Autowired
    private SeasonProductOrderHotelMapper orderHotelMapper;

    @Autowired
    private SeasonOrderMapper seasonOrderMapper;
    @Autowired
    private ISeasonOrderTouristService seasonOrderTouristService;

    @DubboReference
    private ISupplierOrderService supplierOrderService;

    @DubboReference
    private ISysUserService iSysUserService;





    @Override
    public void saveHotelProduct(List<SeasonProductOrderHotelDTO> hotelList, Long userId, Long orderId) {
        LocalDateTime now=LocalDateTime.now();
        List<SeasonProductOrderHotel> list=hotelList.stream().map(
                hotelReq->{
                    SeasonProductOrderHotel hotel= EntityUtil.copy(hotelReq,SeasonProductOrderHotel.class);
                    hotel.setCreateId(userId);
                    hotel.setGmtCreate(now);
                    hotel.setIsDeleted(IsDeletedCode.NO.getCode());
                    hotel.setSeasonOrderId(orderId);
                    hotel.setId(SnowflakeIdWorker.nextId());
                    return hotel;
                }
        ).collect(Collectors.toList());

        orderHotelMapper.insertBatchSomeColumn(list);
    }

    /* @MethodName: 获取酒店订单信息
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/30 16:30
     **/
    @Override
    public List<SeasonProductOrderHotelDTO> getOrderHotelList(Long id) {
        List<SeasonProductOrderHotelDTO> resultList=EntityUtil.copyList(
                orderHotelMapper.selectList(
                        new QueryWrapper<SeasonProductOrderHotel>().lambda()
                                .eq(SeasonProductOrderHotel::getSeasonOrderId,id)
                                .eq(SeasonProductOrderHotel::getIsDeleted,IsDeletedCode.NO.getCode())

                ), SeasonProductOrderHotelDTO.class);

        return resultList;
    }

    /* @MethodName: 下供应商预订单
     * @Description: TODO
     * @Param: 
     * @Return: 
     * @Author: 杨林
     * @Date:2021/4/7 14:19
    **/
    @Override
    public void playSupplierOrder(Long orderId, TokenUser tokenUser) {
        SeasonOrder  seasonOrder=getSeasonOrderById(orderId);
        //旅客信息
        List<SeasonOrderTouristDataDTO> touristList= seasonOrderTouristService.getTouristList(orderId);
        //是否是同一供应商（判读条件 主订单的 供应商id(就是负责人的部门id) 是否与机票一直）
        boolean ifEqualSupplier=true;
        //获取当前用户信息
        UserDTO user = iSysUserService.getUser(new UserDTO().setId(tokenUser.getId()));
        UserDTO chargeDto=iSysUserService.getUser(new UserDTO().setId(seasonOrder.getChargeUserId()));
        Long deptId=chargeDto.getDeptId();
        List<SeasonProductOrderHotelDTO>  hotelList=getOrderHotelList(orderId);
        if(!CollectionUtils.isEmpty(hotelList)){
            SeasonProductOrderHotelDTO hotelDto1=hotelList.get(0);
            if(!hotelDto1.getSupplierId().equals(deptId)){
                ifEqualSupplier=false;
            }
            playSupplierHotelOrder(seasonOrder,touristList,hotelList,hotelDto1.getSupplierId(),hotelDto1.getSupplierName(),user);
            if(!ifEqualSupplier){//不是同一供应商 再次发起供应商预订单 只是供应商id 不同
                String depName=chargeDto.getDept();
                playSupplierHotelOrder(seasonOrder,touristList,hotelList,deptId,depName,user);
            }
        }
    }

    
    /* @MethodName: 下酒店的 供应商预订单
     * @Description: TODO
     * @Param: 
     * @Return: 
     * @Author: 杨林
     * @Date:2021/4/12 14:29
    **/
    private void playSupplierHotelOrder(SeasonOrder seasonOrder, List<SeasonOrderTouristDataDTO> touristList, List<SeasonProductOrderHotelDTO> hotelList, Long SupplierId, String SupplierName, UserDTO user) {
        SupplierOrderSystemHotelAddReq hotelReq=new SupplierOrderSystemHotelAddReq();
        SeasonProductOrderHotelDTO hotelDto1=hotelList.get(0);
        //订单类型
        hotelReq.setOrderType(1);
        //供应商ID不能为空
        hotelReq.setSupplierId(SupplierId);
        //供应商名称
        hotelReq.setSupplierName(SupplierName);
        //供应商订单类型不能为空 1:普通订单,2:内部挂账订单
        hotelReq.setSupplierOrderType("2");
        //供应商销售编号/部门ID(根据'供应商订单编号'显示，1：供应商销售编号，2：部门ID)
        hotelReq.setOriginalSaleNumber(String.valueOf(user.getDeptId()));
        //业务类型不能为空
        hotelReq.setBusinessType(SystemBusinessType.HOTEL.getCode());
        //预订类型
        hotelReq.setReserveTypeId(SupplierReserveTypeEnum.HOTEL.getId());
        //产品类型
        hotelReq.setProductType(ProductType.MANUAL_ENTRY.getCode());
        //资源所属部门ID
        hotelReq.setDepartmentId(user.getDeptId());
        //资源所属部门
        hotelReq.setDepartment(user.getDept());
        //销售单号
        hotelReq.setSaleNumber(seasonOrder.getOrderNumber());
        //产品编号(通用)
        hotelReq.setProductNumber(String.valueOf(hotelDto1.getProductId()));
        //产品名称
        hotelReq.setProductNumber(seasonOrder.getProductName());
        //总金额
        hotelReq.setTotalFee(seasonOrder.getOrderAmount());
        //币种id
        hotelReq.setCurrencyId(Currency.HKD.getCode());
        //币种
        hotelReq.setCurrency(Currency.HKD.getCurrency());
        //应付金额不能为空
        hotelReq.setPayableAmount(seasonOrder.getReceivableAmount());

        //付款类型ID不能为空
        //hotelReq.setPayTypeId();

        List<SupplierSystemOrderHotelTouristAddReq>  sysList=new LinkedList<>();
        for(SeasonOrderTouristDataDTO dataDto:touristList){
            SupplierSystemOrderHotelTouristAddReq touristAddReq=new SupplierSystemOrderHotelTouristAddReq();
            touristAddReq.setTouristId(dataDto.getId());
            touristAddReq.setTouristName(dataDto.getTouristName());
            touristAddReq.setTouristTypeId(dataDto.getTouristTypeId());
            touristAddReq.setTouristType(dataDto.getTouristType());
            touristAddReq.setContactMobile(dataDto.getContactMobile());
            touristAddReq.setContactAreaCode(dataDto.getContactMobileAreaCode());
            touristAddReq.setCertificatesJson(dataDto.getTouristCertificateJson());
            touristAddReq.setGender(dataDto.getGender());
            sysList.add(touristAddReq);
        }

        List<SupplierSystemOrderHotelCheckInAddReq>  reqList=new LinkedList<>();
        for(SeasonProductOrderHotelDTO hotelDto:hotelList){
            SupplierSystemOrderHotelCheckInAddReq  addReq=new SupplierSystemOrderHotelCheckInAddReq();
            addReq.setHotelId(hotelDto.getHotelProductId());
            addReq.setHotelName(hotelDto.getHotelName());
            addReq.setProductId(hotelDto.getProductId());
            addReq.setProductName(hotelDto.getHotelName());
            addReq.setCheckInTime(hotelDto.getOccupancyDate().atStartOfDay());
            addReq.setCheckOutTime(hotelDto.getDepartureDate().atStartOfDay());
            addReq.setNum(hotelDto.getRoomsNumber());
            addReq.setRoomTypeId(hotelDto.getRoomTypeId());
            addReq.setSuitablePeople(hotelDto.getApplicableCrowdName());
            addReq.setSupplierSystemOrderHotelTouristAddReqList(sysList);
            reqList.add(addReq);

        }
        hotelReq.setSupplierSystemOrderHotelCheckInAddReqList(reqList);

        supplierOrderService.addSystemHotel(hotelReq,user.getId());

    }

    /* @MethodName: 动态套票 下各自订单后 确认对应状态
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/14 10:57
     **/
    @Override
    public void changeAffirmState(Long orderId, Integer isAffirm) {
        UpdateWrapper<SeasonProductOrderHotel> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().eq(SeasonProductOrderHotel::getOrderId,orderId);
        updateWrapper.lambda().set(SeasonProductOrderHotel::getScheduledStatus,isAffirm);
        orderHotelMapper.update(null,updateWrapper);
    }

    /* @MethodName: 退款状态
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/20 10:25
     **/
    @Override
    public void changeCancelOrderState(Long orderId, Integer cancelStatus) {
        UpdateWrapper<SeasonProductOrderHotel> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().eq(SeasonProductOrderHotel::getOrderId,orderId);
        updateWrapper.lambda().set(SeasonProductOrderHotel::getCancelStatus,cancelStatus);
        orderHotelMapper.update(null,updateWrapper);
    }



    /* @MethodName: 固定套票下单 走 内部挂账形式
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/21 13:56
     **/
    @Override
    public void playInternalOrder(Long orderId, TokenUser user) {

    }

    /* @MethodName: 动态套票 下酒店订单
     * @Description: TODO
     * @Param: 
     * @Return: 
     * @Author: 杨林
     * @Date:2021/4/21 15:47
    **/
    @Override
    public void playHotelOrder(Long orderId, TokenUser user, List<SeasonOrderPayDTO> payList) {
        
    }


    public SeasonOrder getSeasonOrderById(Long id){
        return seasonOrderMapper.selectById(id);
    }
}
